﻿using System;
using System.ComponentModel;
using System.Web.UI;
using System.Web.UI.WebControls.WebParts;
using ZhukBlogLinqExamples.Model;
using ZhukBlogLinqExamples.Repositories;

namespace ZhukBlogLinqExamples.WebParts.CrossSiteCollectionDataQuery
{
    ///<summary>
    /// Web part retrieving data from another site collection
    ///</summary>
    [ToolboxItemAttribute(false)]
    public class CrossSiteCollectionDataQuery : WebPart
    {
        protected override void CreateChildControls()
        {
            try
            {
                var repository1 = new EmployeeRepository("http://SharePointServer/linq", true, true);
                var items1 = repository1.GetEntityCollection();
                foreach (var employee in items1)
                {
                    RenderEmployeeInfo(employee);
                }
                Controls.Add(new LiteralControl("***<br/>"));
                var repository2 = new EmployeeRepository("http://SharePointServer/sites/asc", true, false);
                var items2 = repository2.GetEntityCollection();
                foreach (var employee in items2)
                {
                    RenderEmployeeInfo(employee);
                }
            }
            catch (Exception ex)
            {
                Controls.Add(new LiteralControl(ex.ToString()));
            }
        }

        private void RenderEmployeeInfo(Employee employee)
        {
            Controls.Add(new LiteralControl("ServerUrl: " + employee.ServerUrl + "<br/>"));
            Controls.Add(new LiteralControl("Path: " + employee.Path + "<br/>"));
            Controls.Add(new LiteralControl("Title: " + employee.Title + "<br/>"));
        }
    }
}
